package net.example.lesson3;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestSubject {
    public static void main(String[] args) {
        String name = "朱海";
        //创建一个实例对象，这个对象是被代理的对象
        SubjectDemo subject = new TestSubjectImpl();

        final MyInvocationHandler1 myInvocationHandler1 = new MyInvocationHandler1(new TestSubjectImpl());

        final SubjectDemo subjectProxy = (SubjectDemo)Proxy.newProxyInstance(TestSubjectImpl.class.getClassLoader(),
                TestSubjectImpl.class.getInterfaces(), myInvocationHandler1);

        subjectProxy.add(name);

        subjectProxy.show(name);

        subjectProxy.delete(name);

    }
}

/**
 * SubjectDemo.
 */
interface SubjectDemo {
    void add(final String name);

    String show(final String name);

    void delete(final String name);
}

/**
 * 被代理类.
 */
class TestSubjectImpl implements SubjectDemo {
    @Override
    public void add(final String name){
        String.format("%s执行了%s方法。", name, "add");
    }

    @Override
    public String show(final String name){
        String.format("%s执行了%s方法。", name, "show");
        return "显示名字："+ name;
    }

    @Override
    public void delete(final String name){
        String.format("%s执行了%s方法。", name, "delete");
    }
}

/**
 * 代理类
 */
class MyInvocationHandler1 implements InvocationHandler {
    private Object target;

    public MyInvocationHandler1(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        String.format("代理执行%s方法之前，打印日志。", method.getName());
        Object ressult = method.invoke(target, args);
        String.format("代理执行%s方法之后，打印日志。", method.getName());
        return ressult;
    }
}
